import java.net.*;
import java.io.*;
import java.util.Scanner;

class Network {
   private Scanner in;
   private PrintWriter out;

   // Server Socket
   public Network (int port) throws IOException{
      ServerSocket serverSocket = new ServerSocket (port);
      Socket clientSocket = serverSocket.accept();

      // use the InputStream object to create a Scanner.
      in = new Scanner (clientSocket.getInputStream());

      // use the OutputStream object to create a PrintWriter
      out = new PrintWriter (clientSocket.getOutputStream(), true);
      out.println ("Hello, world!");


      String line = in.nextLine();
      System.out.println ("I, the server, just received this from " +
                    "the client: " + line);
   }

   // Client Socket
   public Network (String server, int port) throws
                          UnknownHostException, IOException {
      Socket clientSocket = new Socket(server, port);

      // use the InputStream object to create a Scanner.
      in = new Scanner (clientSocket.getInputStream());

      // use the OutputStream object to create a PrintWriter
      out = new PrintWriter (clientSocket.getOutputStream(), true);
      System.out.println ("I the client just received this from the
server: " +
                           in.nextLine());
      out.println ("Hello to you, too");

   }


   public static void main (String args[]) {
      if (args.length > 0) {
         // This is the client socket.
         // The first argument is the server name
         try {
            Network client = new Network (args[0], 4444);
         } catch (UnknownHostException e) {
            System.err.println ("Can't connect to server " + args[0] + e);
         } catch (IOException e) {
            System.err.println ("Could not connect to port 4444 on server: "
                                + args[0] + ": " + e);
         }

      } else {
         // This is the server socket.
         try {
            Network server = new Network (4444);
         } catch (IOException e) {
            System.err.println ("Could not connect to port 4444: " + e);
         }
      }
   }
}
